﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Calculator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
      

        }

        #region 属性
        /// <summary>
        /// 第一个计算值 
        /// </summary>
        public string Number1 { get; set; } = "";
        /// <summary>
        /// 第二个计算值 
        /// </summary>
        public string Number2 { get; set; } = "";

        /// <summary>
        /// 操作运算符
        /// </summary>
        public MyEnumOP OP { get; set; } = MyEnumOP.Unknow;

        public double? ResultNumber { get; set; } 

        public string JiSuanShi { get; set; } = "";

        public string RefreshJiSuanShi() {

            if (OP != MyEnumOP.Unknow) 
            {
                if (Number2 == null)
                {

                    return $@"{Number1}{GetOPString(OP)}";

                }
                else
                {
                    return $@"{Number1}{GetOPString(OP)}{Number2}=";
                }
              

            }
            else
            {


                return "";
            }
            
        }

        #endregion

        #region 方法

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oldV"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        public bool GetValue(string v, out double res)
        {
            var parseRes = double.TryParse(v, out var result);

            res = result;

            return parseRes;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //如果 操作运算符为未知，则增加到第一个数
            //否则 增加到第二个数。

            var num = (sender as Button).Content;

            ButtonClickRun(num);
            //MessageBox.Show((sender as Button).Content.ToString());
        }

        private void ButtonClickRun(object num)
        {
            if (OP == MyEnumOP.Unknow)
            {
                var tempRes = GetValue($@"{Number1}{num.ToString()}", out double d);
                if (tempRes)
                {
                    Number1 = $@"{Number1}{num.ToString()}";
                    if (Number1.StartsWith("0") && Number1.StartsWith("0.")==false)
                    {
                        Number1 = Number1.Substring(1);
                    }
                    labResult.Content = Number1.ToString();
                }
            }
            else
            {
                var tempRes = GetValue($@"{Number2}{num.ToString()}", out double d);
                if (tempRes)
                {
                    Number2 = $@"{Number2}{num.ToString()}";
                    if (Number2.StartsWith("0") && Number2.StartsWith("0.") == false && Number2!="0")
                    {
                        Number2 = Number2.Substring(1);
                    }

                    labResult.Content = Number2.ToString();

                }
            }

            labJiSuanShi.Content = RefreshJiSuanShi();
        }


        public string GetOPString(MyEnumOP myEnumOP)
        {
            string res = "";
            switch (myEnumOP)
            {
                case MyEnumOP.Add:
                    res = "+";
                    break;
                case MyEnumOP.Subtract:
                    res = "-";
                    break;
                case MyEnumOP.Multiply:
                    res = "x";
                    break;
                case MyEnumOP.Divide:
                    res = "÷";
                    break;
                case MyEnumOP.Square:
                    res = "^2";
                    break;
                case MyEnumOP.SquareRoot:
                    res = "√";
                    break;
                case MyEnumOP.Unknow:
                    break;
            }

            return res;

        }

        private void Button_Click_OP(object sender, RoutedEventArgs e)
        {
            if (Number1 == null)
            {
                return;
            }


            //有数据时先计算结果 再进行下一步
            if (OP != MyEnumOP.Unknow && Number2 != null)
            {

                Calc();

            }


          
            var tempop = (sender as Button).Content;

            BtnOpRun(tempop);
        }

        private void BtnOpRun(object tempop)
        {
            if (tempop.ToString() == "+")
            {
                OP = MyEnumOP.Add;
            }

            if (tempop.ToString() == "-")
            {
                OP = MyEnumOP.Subtract;
            }

            if (tempop.ToString() == "X")
            {
                OP = MyEnumOP.Multiply;
            }

            if (tempop.ToString() == "÷")
            {
                OP = MyEnumOP.Divide;
            }

            labJiSuanShi.Content = RefreshJiSuanShi();
        }

        /// <summary>
        /// 移除最后一位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_RemoveLast(object sender, RoutedEventArgs e)
        {
            try
            {
                if (OP == MyEnumOP.Unknow)
                {
                    if (Number1!=null)
                    {
                        labResult.Content = Number1.ToString().Substring(0, Number1.ToString().Length - 1);
                        if (!string.IsNullOrWhiteSpace(labResult.Content.ToString()))
                        {
                            Number1 = labResult.Content.ToString();// double.Parse(labResult.Content.ToString());
                        }

                    }


                }
                else
                {
                    if (Number2 != null)
                    {
                        labResult.Content = Number2.ToString().Substring(0, Number2.ToString().Length - 1);
                        if (!string.IsNullOrWhiteSpace(labResult.Content.ToString()))
                        {
                            Number2 = labResult.Content.ToString();//
                        }
                    }




                }
                labJiSuanShi.Content = RefreshJiSuanShi();

            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
          
            }
       
        }

        private void Button_Click_Calc(object sender, RoutedEventArgs e)
        {
            Calc();
        }

        private void Calc()
        {
            try
            {
                //计算结果 再进行下一步
                if (OP != MyEnumOP.Unknow && !string.IsNullOrWhiteSpace(Number2))
                {
                    var res = 0.0;
                    var num1 = double.Parse(Number1.ToString());
                    var num2 = double.Parse(Number2.ToString());
                    switch (OP)
                    {
                        case MyEnumOP.Add:

                            res = num1 + num2;
                            break;
                        case MyEnumOP.Subtract:

                            res = (double)(num1 - num2);
                            break;
                        case MyEnumOP.Multiply:

                            res = (double)(num1 * num2);
                            break;
                        case MyEnumOP.Divide:
                            if (num2 == 0)
                            {
                                labResult.Content = "除数不能为0";
                                Number2 = null;
                                return;
                            }
                            res = (double)(num1 / num2);
                            break;
                        case MyEnumOP.Square:
                            res = (double)(num1 * num1);
                            break;
                        case MyEnumOP.SquareRoot:
                            res = (double)(Math.Sqrt(num1));
                            break;
                        case MyEnumOP.Unknow:
                            break;
                    }
                    ResultNumber = res;
                    ListHistory.Items.Insert(0, $@"{RefreshJiSuanShi()}{res}");
                    Number1 = null;
                    Number2 = null;
                    OP = MyEnumOP.Unknow;
                    labResult.Content = res.ToString();


                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
         
        }

        private void Button_Click_Clear(object sender, RoutedEventArgs e)
        {
            labJiSuanShi.Content = "";
            labResult.Content = "0";
            OP = MyEnumOP.Unknow;
            Number2 = null;
            Number1 = null;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Number1 == null)
                {
                    return;
                }
                if (OP == MyEnumOP.Unknow)
                {
                    var num1 = double.Parse(Number1.ToString()) * -1;
                    Number1 = num1.ToString();
                    labResult.Content = Number1;

                }
                else
                {
                    var num2 = double.Parse(Number2.ToString()) * -1;
                    Number2 = num2.ToString();
                    labResult.Content = Number2;
                }

                labJiSuanShi.Content = RefreshJiSuanShi();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
    

        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_ClearEmpty(object sender, RoutedEventArgs e)
        {
            try
            {

                if (OP == MyEnumOP.Unknow)
                {
                    Number1 = "0";
                    labResult.Content = "0";
                }
                else
                {
                    Number2 = "0";
                    labResult.Content = "0";

                }
                labJiSuanShi.Content = RefreshJiSuanShi();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
  

        }

        private void Button_Click_Percent(object sender, RoutedEventArgs e)
        {
            try
            {
              
                if (OP == MyEnumOP.Unknow)
                {
                    var num1 = double.Parse(labResult.Content.ToString()) * 100.0;
                    if (num1<100)
                    {
                        labResult.Content = num1;
                    }
                

                }
             
              
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
            
        }

        private void Button_Click_1x(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Number1 == null)
                {
                    return;
                }
                if (OP == MyEnumOP.Unknow)
                {
                    var num1 = 1 / double.Parse(Number1.ToString());
                    Number1 = num1.ToString();
                    labResult.Content = Number1;

                }
                else
                {
                    var num2 = 1 / double.Parse(Number2.ToString());
                    Number2 = num2.ToString();
                    labResult.Content = Number2;

                }
                labJiSuanShi.Content = RefreshJiSuanShi();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
           
        }

        private void Button_Click_Pow(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Number1 == null)
                {
                    return;
                }
                if (OP == MyEnumOP.Unknow)
                {
                    var num1 = Math.Pow(double.Parse(Number1.ToString()), 2.0);
                    Number1 = num1.ToString();
                    labResult.Content = Number1;

                }
                else
                {
                    var num2 = Math.Pow(double.Parse(Number2.ToString()), 2.0);
                    Number2 = num2.ToString();
                    labResult.Content = Number2;

                }
                labJiSuanShi.Content = RefreshJiSuanShi();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
           
        }

        private void Button_Click_Sqrt(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Number1==null || Number2==null)
                {
                    return;
                }
                if (OP == MyEnumOP.Unknow)
                {
                    var num1 = Math.Sqrt(double.Parse(Number1.ToString()));
                    Number1 = num1.ToString();
                    labResult.Content = Number1;

                }
                else
                {
                    var num2 = Math.Sqrt(double.Parse(Number2.ToString()));
                    Number2 = num2.ToString();
                    labResult.Content = Number2;

                }
                labJiSuanShi.Content = RefreshJiSuanShi();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
           
        }



        #endregion

        private void ListHistory_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var tempHistory = ListHistory.SelectedIndex;
            var HistoryString= ListHistory.Items[tempHistory].ToString().Split('=');

            labJiSuanShi.Content = HistoryString[0] + "=";
            labResult.Content = HistoryString[1];
            Number1= HistoryString[1];
           
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
         
        }

        private void UIElement_OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.NumPad0 || e.Key == Key.D0)
            {
                ButtonClickRun("0");
            }

            if (e.Key == Key.NumPad1 || e.Key == Key.D1)
            {
                ButtonClickRun("1");
            }

            if (e.Key == Key.NumPad2 || e.Key == Key.D2)
            {
                ButtonClickRun("2");
            }

            if (e.Key == Key.NumPad3 || e.Key == Key.D3)
            {
                ButtonClickRun("3");
            }
            if (e.Key == Key.NumPad4 || e.Key == Key.D4)
            {
                ButtonClickRun("4");
            }
            if (e.Key == Key.NumPad5 || e.Key == Key.D5)
            {
                ButtonClickRun("5");
            }
            if (e.Key == Key.NumPad6 || e.Key == Key.D6)
            {
                ButtonClickRun("6");
            }
            if (e.Key == Key.NumPad7 || e.Key == Key.D7)
            {
                ButtonClickRun("7");
            }
            if (e.Key == Key.NumPad8 || e.Key == Key.D8)
            {
                ButtonClickRun("8");
            }
            if (e.Key == Key.NumPad9 || e.Key == Key.D9)
            {
                ButtonClickRun("9");
            }
            if (e.Key == Key.OemPlus)
            {
                BtnOpRun("+");
            }
            if (e.Key == Key.OemMinus)
            {
                BtnOpRun("-");
            }
            if (e.Key == Key.OemSemicolon)
            {
                BtnOpRun("÷");
            }
            if (e.Key == Key.Decimal)
            {
                ButtonClickRun(".");
            }
            if (e.Key == Key.Multiply)
            {
                BtnOpRun("X");
            }
            if (e.Key == Key.Divide)
            {
                BtnOpRun("÷");
            }
            if (e.Key == Key.Divide)
            {
                BtnOpRun("÷");
            }

            if (e.Key == Key.Enter)
            {
                Button_Click_Calc(null,null);
            }

            if (e.Key == Key.Escape)
            {
                Button_Click_ClearEmpty(null,null);
            }
            if (e.Key == Key.Back)
            {
                Button_Click_Clear(null, null);
            }


        }
    }

    /// <summary>
    /// 操作运算符
    /// </summary>
    public enum MyEnumOP
    {
        
        Add,
        Subtract,
        Multiply,
        Divide,
        Square,
        SquareRoot,     
        Unknow

    }




}
